import WechatJSSDK from "wechat-jssdk/dist/client.umd";
import { getWechatConfig, wechatAuth } from "@api/public";
import { parseQuery } from "@utils";
import localStorage from "../utils/store/localStorage";
import {VUE_APP_WX_APP_ID} from "@utils"
import md5 from "md5";
import {checkWXOpenId, getWXUserInfo} from "../api/user";
const STATE_KEY = "wx_authorize_state";
const WX_AUTH = "wx_auth";
let instance;
let wechatObj;

export default function wechat() {
  return new Promise((resolve, reject) => {
    if (instance) return resolve(instance);
    getWechatConfig()
      .then(res => {
        const config = Object.assign({}, res.data, {
          "appId": VUE_APP_WX_APP_ID
        });
        const _wx = WechatJSSDK(config);
        wechatObj = _wx;
        _wx
          .initialize()
          .then(() => {
            instance = _wx.wx;
            instance.initConfig = config;
            resolve(instance);
          })
          .catch(reject);
      })
      .catch(err => {
        console.log(err);
        reject(err);
      });
  });
}

export function clearAuthStatus() {
  localStorage.remove(WX_AUTH);
  localStorage.remove(STATE_KEY);
}

export function oAuth() {
  const { code } = parseQuery();
  if (!code) return toAuth();
}

export function auth(code) {
  return new Promise((resolve, reject) => {
    wechatAuth(code)
        .then(res => {
          const obj = JSON.parse(res.data.token);
          localStorage.set('access_token', obj.access_token);
          localStorage.set('openid', obj.openid);
          getWXUserInfo(obj.access_token, obj.openid).then(res => {
            const wxUser = JSON.parse(res.data);
            localStorage.set('wxUser', wxUser);
            const openid = localStorage.get('openid')
            checkWXOpenId(openid, wxUser.headimgurl, wxUser.nickname).then(response => {
              if (response.code) {
                const tokenStr = response.data.jwttoken.split(".");
                const t = md5(tokenStr[1] + response.data.jwtrandomKey);
                const jwttoken = response.data.jwttoken;
                localStorage.set("token", jwttoken);
                localStorage.set("sign", t);
                if (localStorage.get("sign")) {
                  resolve(response.data.userId)
                }
              } else if (response.msg == "进行手机绑定") {
                reject()
              }
            })
          })
        })
        .catch(reject);
  });
}

export function toAuth() {
    location.href = getAuthUrl(VUE_APP_WX_APP_ID);
}

function getAuthUrl(appId) {
  const redirect_uri = encodeURIComponent(
      `${location.origin}/manager/wechatLogin`
  );
  const state = encodeURIComponent(
      ("" + Math.random()).split(".")[1] + "authorizestate"
  );
  return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
}

function toPromise(fn, config = {}) {
  return new Promise((resolve, reject) => {
    fn({
      ...config,
      success(res) {
        resolve(res);
      },
      fail(err) {
        reject(err);
      },
      complete(err) {
        reject(err);
      },
      cancel(err) {
        reject(err);
      }
    });
  });
}

export function pay(config) {
  return toPromise(instance.chooseWXPay, config);
}

export function openAddress() {
  return new Promise((resolve, reject) => {
    wechatEvevt("openAddress", {})
      .then(res => {
        console.log(res);
        resolve(res);
      })
      .catch(res => {
        console.log(res);
        if (res.is_ready) {
          res.wx.openAddress({
            fail(res) {
              reject(res);
            },
            success(res) {
              resolve(res);
            }
          });
        } else {
          reject(res);
        }
      });
  });
}

export function openShareAll(config) {
  config || {};
  config.type = config.type == undefined ? "link" : config.type;
  return new Promise(resolve => {
    getWechatConfig().then(res => {
      wechatObj.signSignature({
        nonceStr: res.data.nonceStr,
        signature: res.data.signature,
        timestamp: res.data.timestamp
      });
      instance = wechatObj.getOriginalWx();
      instance.ready(() => {
        instance.updateAppMessageShareData(config);
        instance.updateTimelineShareData(config);
        resolve();
      });
    });
  });
}

export function openShareAppMessage(config) {
  instance.updateAppMessageShareData(config);
  instance.onMenuShareAppMessage && instance.onMenuShareAppMessage(config);
}

export function openShareTimeline(config) {
  instance.updateTimelineShareData(config);
  instance.onMenuShareTimeline && instance.onMenuShareTimeline(config);
}

/**
 * 公众号事件
 * @param name 事件名
 * @param config 配置
 * @returns {Promise<unknown>}
 */
export function wechatEvevt(name, config) {
  return new Promise((resolve, reject) => {
    let wx;
    let configDefault = {
      fail(res) {
        console.log(res);
        if (wx) return reject({ is_ready: true, wx: wx });
        getWechatConfig().then(res => {
          wechatObj.signSignature({
            nonceStr: res.data.nonceStr,
            signature: res.data.signature,
            timestamp: res.data.timestamp
          });
          wx = wechatObj.getOriginalWx();
          reject({ is_ready: true, wx: wx });
        });
      },
      success(res) {
        resolve(res);
      }
    };
    Object.assign(configDefault, config);
    if (typeof instance !== "undefined") {
      instance.ready(() => {
        if (typeof name === "object") {
          name.forEach(item => {
            instance[item] && instance[item](configDefault);
          });
        } else instance[name] && instance[name](configDefault);
      });
    } else {
      getWechatConfig().then(res => {
        const _wx = WechatJSSDK(res.data);
        _wx.initialize().then(() => {
          instance = _wx.getOriginalWx();
          instance.ready(() => {
            if (typeof name === "object") {
              name.forEach(item => {
                instance[item] && instance[item](configDefault);
              });
            } else instance[name] && instance[name](configDefault);
          });
        });
      });
    }
  });
}

export function ready() {
  return new Promise(resolve => {
    if (typeof instance !== "undefined") {
      instance.ready(() => {
        resolve(instance);
      });
    } else {
      getWechatConfig().then(res => {
        const _wx = WechatJSSDK(res.data);
        _wx.initialize().then(() => {
          instance = _wx.wx;
          instance.ready(() => {
            resolve(instance);
          });
        });
      });
    }
  });
}
